package ge.telasi.tasks.ui.search;

import ge.telasi.tasks.model.Structure;
import ge.telasi.tasks.search.Condition;
import ge.telasi.tasks.ui.UIUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;

/**
 * Structure(s) field.
 * 
 * @author dimitri
 */
public class StructureField extends Field {
    private List<Structure> structures;

    public StructureField(String name, String humanName) {
        super(name, humanName);
    }

    public List<Structure> getStructures() {
        return structures;
    }

    public void setStructures(List<Structure> structures) {
        this.structures = structures;
    }
    
    @Override
    public String getType() {
        return "structure";
    }

    @Override
    public Icon getIcon() {
        return UIUtils.getIcon16x16("application_cascade.png");
    }

    @Override
    public Condition getCondition() {
        // empty condition
        if (structures == null || structures.isEmpty()) {
            return null;
        }

        // create where condition
        StringBuilder b = new StringBuilder();
        Map<String, Object> subst = new HashMap<String, Object>();
        b.append(" ( ");
        b.append(getSysName());
            b.append(" IN ( ");
        boolean first = true;
        for (Structure structure : structures) {
            if (!first) {
                b.append(", ");
            }
            String fieldName = getNextField();
            b.append(":");
            b.append(fieldName);
            subst.put(fieldName, structure.getId());
            first = false;
        }
        b.append(" ) ) ");
        String where = b.toString();

        // build condition
        Condition condition = new Condition();
        condition.setCondition(where);
        condition.getSubstitutions().putAll(subst);
        return condition;
    }

}
